package org.knife.springbootlearn.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.sql.DataSource;

/**
 * 使用数据库连接来实现登陆认证
 * @author tianhao.luo@hand-china.com
 * @version 1.0
 * @date 2021年12月01日 星期三 10:33 下午
 * @description
 * @since 1.0
 */
//@Configuration
public class MyJdbcWebSecurityConfigureAdapter extends WebSecurityConfigurerAdapter {

    // 使用用户名查询密码
    String pwdQuery = "select user_name,pwd,available from t_user where user_name=?";
    // 使用用户名查询角色信息
    String roleQuery = "select u.user_name,r.role_name from t_user u,t_user_role ur,t_role r where u.id=ur.user_id and r.id=ur.role_id and u.user_name=?";

    @Autowired
    private DataSource dataSource;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        auth.jdbcAuthentication().passwordEncoder(passwordEncoder).dataSource(dataSource)
                // 查询用户，自动判断密码
            .usersByUsernameQuery(pwdQuery)
                // 赋予权限
                .authoritiesByUsernameQuery(roleQuery);
    }
}
